package com.nforce.linremote.scripting;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.res.AssetManager;
import android.os.Environment;

import com.nforce.linremote.Constants;
import com.nforce.linremote.model.Program;

public class ScriptManager {

    public static List<Program> loadScripts(AssetManager assetManager, List<String> interfaces) {
	List<Program> programs = new ArrayList<Program>();

	String[] internalFileList = new String[0];
	String[] externalFileList = new String[0];
	try {
	    internalFileList = assetManager.list(Constants.SCRIPTS_PATH_INTERNAL);
	} catch (IOException e) {
	    return Collections.emptyList();
	}

	for (String i : interfaces) {
	    String scriptName = null;
	    String prefix = Constants.SCRIPTS_PATH_INTERNAL + "/";
	    for (String fileName : internalFileList) {
		if (i.contains(fileName)) {
		    if (scriptName == null || (scriptName != null && scriptName.length() < fileName.length())) {
			scriptName = fileName;
		    }
		}
	    }
	    for (String fileName : externalFileList) {
		if (i.contains(fileName)) {
		    if (scriptName == null || (scriptName != null && scriptName.length() <= fileName.length())) {
			scriptName = fileName;
			prefix = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.SCRIPTS_PATH_EXTERNAL + "/";
		    }
		}
	    }
	    if (scriptName != null) {
		programs.add(new Program(i, prefix + scriptName, false));
	    }
	}

	return programs;
    }

}
